﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Web;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Text.RegularExpressions;
namespace PeekService
{
  
   public static class CommonService
    {
     
       /// <summary>
       /// 发送邮件方法
       /// </summary>
       /// <param name="toadd"></param>
       /// <param name="sb">正文</param>
       /// <param name="subject">标题</param>
       /// <returns></returns>
       public static bool SendEmail(string toadd, string sb, string subject,SendType sendType)
       {
           try
           {
               string type = "";
               switch (sendType)
               {
                   case SendType.Message: type = "留言邮箱"; break;
                   case SendType.Ticket: type = "门票邮箱"; break;
                   case SendType.Service: type = "客服邮箱"; break;
                   case SendType.Sys: type = "系统邮箱"; break;
                   case SendType.Other: type = "其他"; break;

               }
               SysConfig sysConfig = new SysConfigService().GetAll().Find(o => o.EmailType == type);
               MailAddress from = new MailAddress(sysConfig.Email);
               MailAddress to = new MailAddress(toadd);
               MailMessage message = new MailMessage(from, to);
               message.Subject = subject;//标题
               message.IsBodyHtml = true;
               message.Body = sb;//正文 
               SmtpClient client = new SmtpClient(sysConfig.SMTP);//设置smtp服务器，这里是新浪的。
               client.Credentials = new System.Net.NetworkCredential(sysConfig.Email, sysConfig.EmailPwd);//设置登录stmp服务器的用户名和密码，前面填帐号比如liuxiaoping.com.cn，后面的是该邮箱密码。
               client.Send(message); message.Dispose(); return true;
           }
           catch
           {
               return false;
           }
       }

       #region HTML字符串缩略方法
       private const int N_STRINGRESTRIC_Length = 14;
       /// <summary>
       ///  HTML字符串缩略方法
       /// </summary>
       /// <param name="strVal">需要缩略的字符串</param>
       /// <returns>缩略后的结果(String...)</returns>
       public static string StringRestric(string strVal)
       {
           return CommonService.StringRestric(strVal, N_STRINGRESTRIC_Length);
       }

       /// <summary>
       /// HTML字符串缩略方法
       /// </summary>
       /// <param name="strVal">需要缩略的字符串</param>
       /// <param name="len">缩略起始索引</param>
       /// <returns>缩略后的结果(String...)</returns>
       public static string StringRestric(string strVal, int len)
       {
           string result = "";

           string strDecode = HttpContext.Current.Server.HtmlDecode(strVal);

           if (strDecode != null && strDecode.Length > len)
           {
               result = "<span title=\"" + TitleAutoBreak(strVal, 24) + "\">" + strDecode.Substring(0, len) + "...</span>";
           }
           else
           {
               result = strDecode;
           }

           return result;
       }

       /// <summary>
       /// HTML字符串缩略方法
       /// </summary>
       /// <param name="strVal">需要缩略的字符串</param>
       /// <param name="len">缩略起始索引</param>
       /// <param name="title">指定提示信息</param>
       /// <returns>缩略后的结果(String...)</returns>
       public static string StringRestric(string strVal, int len, string title)
       {
           string result = "";

           string strDecode = HttpContext.Current.Server.HtmlDecode(strVal);

           if (strDecode != null && strDecode.Length > len)
           {
               string tempStr = String.Empty;
               if (title.Length > 300)
               {
                   tempStr = strDecode.Substring(0, len);
                   if (tempStr.LastIndexOf('<') <= tempStr.LastIndexOf('>'))
                   {
                       result = "<span title=\"" + title.Substring(0, 300) + "..." + "\">" + tempStr + "...</span>";
                   }
                   else
                   {
                       tempStr = tempStr.Substring(0, tempStr.LastIndexOf('<'));
                       result = "<span title=\"" + title.Substring(0, 300) + "..." + "\">" + tempStr + "...</span>";
                   }
               }
               else
               {
                   tempStr = strDecode.Substring(0, len);
                   if (tempStr.LastIndexOf('<') <= tempStr.LastIndexOf('>'))
                   {
                       result = "<span title=\"" + title + "\">" + tempStr + "...</span>";
                   }
                   else
                   {
                       tempStr = tempStr.Substring(0, tempStr.LastIndexOf('<'));
                       result = "<span title=\"" + title + "\">" + tempStr + "...</span>";
                   }
               }
           }
           else
           {
               result = strDecode;
           }

           return result;
       }

       /// <summary>
       /// HTML字符串缩略方法
       /// </summary>
       /// <param name="strVal">需要缩略的字符串</param>
       /// <param name="len">缩略起始索引</param>
       /// <param name="TitleLen">titlelen</param>
       /// <returns>缩略后的结果(String...)</returns>
       public static string StringRestric(string strVal, int len, int TitleLen)
       {
           string result = "";

           string strDecode = HttpContext.Current.Server.HtmlDecode(strVal);

           if (strDecode != null && strDecode.Length > len)
           {
               string tempStr = String.Empty;

               tempStr = strDecode.Substring(0, len);
               if (tempStr.LastIndexOf('<') <= tempStr.LastIndexOf('>'))
               {
                   result = "<span title=\"" + TitleAutoBreak(strVal, TitleLen) + "..." + "\">" + tempStr + "...</span>";
               }
               else
               {
                   tempStr = tempStr.Substring(0, tempStr.LastIndexOf('<'));
                   result = "<span title=\"" + TitleAutoBreak(strVal, TitleLen) + "..." + "\">" + tempStr + "...</span>";
               }
           }
           else
           {
               result = strDecode;
           }
           result.Replace("\"", "&quot;");
           return result;
       }

       /// <summary>
       /// html标签title属性折行
       /// </summary>
       /// <param name="Title"></param>
       /// <param name="Length"></param>
       /// <returns></returns>
       public static string TitleAutoBreak(string Title, int Length)
       {
           int nTotalLen = Title.Length;
           if (nTotalLen > Length)
           {
               StringBuilder sbTitle = new StringBuilder();
               for (int i = 0; i < nTotalLen; i += Length)
               {

                   if (i + Length > nTotalLen)
                       sbTitle.Append(Title.Substring(i)).Append("&#13;");
                   else
                       sbTitle.Append(Title.Substring(i, Length)).Append("&#13;");
               }
               if (sbTitle.Length > 0)
                   return sbTitle.ToString();
           }
           return Title;
       }
       #endregion
       /// <summary>
       /// 将object类型转换成json格式
       /// </summary>
       /// <param name="obj"></param>
       /// <returns></returns>
       public static string ConvertToJSON(object obj)
       {
           return JsonConvert.SerializeObject(obj);
       }

       /// <summary>
       /// 弹出提示框方法
       /// </summary>
       /// <param name="page"></param>
       /// <param name="msg"></param>
       public static void ShowAlert(System.Web.UI.Page page, string msg)
       {
           System.Text.StringBuilder Builder = new System.Text.StringBuilder();
           Builder.Append("<script language='javascript' defer>");
           Builder.AppendFormat("alert('{0}');", msg);
           Builder.Append("</script>");
           page.ClientScript.RegisterStartupScript(page.GetType(), "message", Builder.ToString());
       }
       /// <summary>
       /// 字符串html编码
       /// </summary>
       /// <param name="str"></param>
       /// <returns></returns>
       public static string HTMLEncode(string str)
       {
           return HttpContext.Current.Server.HtmlEncode(str);
       }
       /// <summary>
       /// 字符串HTML解码
       /// </summary>
       /// <param name="str"></param>
       /// <returns></returns>
       public static string HTMLDecode(string str)
       {
           return HttpContext.Current.Server.HtmlDecode(str);
       }
      /// <summary>
       /// 将输入字符串中的sql敏感字，替换成"[敏感字]"，要求输出时，替换回来
      /// </summary>
      /// <param name="inputString"></param>
      /// <returns></returns>
       public static string EncodeSQLStr(string inputString)
       {
           //要替换的敏感字
           string SqlStr = @"and|or|exec|execute|insert|select|delete|update|alter|create|drop|count|\*|chr|char|asc|mid|substring|master|truncate|declare|xp_cmdshell|restore|backup|net +user|net +localgroup +administrators";
           try
           {
               if ((inputString != null) && (inputString != String.Empty))
               {
                   string str_Regex = @"\b(" + SqlStr + @")\b";
                   Regex Regex = new Regex(str_Regex, RegexOptions.IgnoreCase);             
                   MatchCollection matches = Regex.Matches(inputString);
                   for (int i = 0; i < matches.Count; i++)
                       inputString = inputString.Replace(matches[i].Value, "[" + matches[i].Value + "]");
               }
           }
           catch
           {
               return "";
           }
           return inputString;

       }
      /// <summary>
       /// 将已经替换成的"[敏感字]"，转换回来为"敏感字"
      /// </summary>
      /// <param name="outputstring"></param>
      /// <returns></returns>
       public static  string DecodeSQLStr(string outputstring)
       {
           //要替换的敏感字
           string SqlStr = @"and|or|exec|execute|insert|select|delete|update|alter|create|drop|count|\*|chr|char|asc|mid|substring|master|truncate|declare|xp_cmdshell|restore|backup|net +user|net +localgroup +administrators";
           try
           {
               if ((outputstring != null) && (outputstring != String.Empty))
               {
                   string str_Regex = @"\[\b(" + SqlStr + @")\b\]";
                   Regex Regex = new Regex(str_Regex, RegexOptions.IgnoreCase);
                   MatchCollection matches = Regex.Matches(outputstring);
                   for (int i = 0; i < matches.Count; i++)
                       outputstring = outputstring.Replace(matches[i].Value, matches[i].Value.Substring(1, matches[i].Value.Length - 2));

               }
           }
           catch
           {
               return "";
           }
           return outputstring;
       }
       /// <summary>
       /// 防止脚本注入方法
       /// </summary>
       /// <param name="inputStr"></param>
       /// <returns></returns>
       public static string PreventJsInjection(string inputStr)
       {
           System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"<script[\s\S]+</script *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
           System.Text.RegularExpressions.Regex regex2 = new System.Text.RegularExpressions.Regex(@" href *= *[\s\S]*script *:", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
           System.Text.RegularExpressions.Regex regex3 = new System.Text.RegularExpressions.Regex(@" no[\s\S]*=", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
           System.Text.RegularExpressions.Regex regex4 = new System.Text.RegularExpressions.Regex(@"<iframe[\s\S]+</iframe *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
           System.Text.RegularExpressions.Regex regex5 = new System.Text.RegularExpressions.Regex(@"<frameset[\s\S]+</frameset *>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);      
           System.Text.RegularExpressions.Regex regex6 = new System.Text.RegularExpressions.Regex(@"<[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
           inputStr = regex1.Replace(inputStr, ""); //过滤<script></script>标记
           inputStr = regex2.Replace(inputStr, ""); //过滤href=java script: (<A>) 属性
           inputStr = regex3.Replace(inputStr, " _disibledevent="); //过滤其它控件的on...事件
           inputStr = regex4.Replace(inputStr, ""); //过滤iframe
           inputStr = regex5.Replace(inputStr, ""); //过滤frameset        
           inputStr = regex6.Replace(inputStr, "");//过滤标签                   
           return inputStr;
       }
    }
   public enum SendType { Message,Ticket,Service,Sys,Other}
}
